import { Graph } from '@antv/x6'

const _createCtrlKey = (key: string, shift = false) => {
  return shift
    ? [`meta+shift+${key}`, `ctrl+shift+${key}`]
    : [`meta+${key}`, `ctrl+${key}`]
}

export default function registerKeyboardEvent (graph: Graph) {
  // #region 复制 剪切 粘贴
  graph.bindKey(_createCtrlKey('c'), () => {
    const cells = graph.getSelectedCells()
    if (cells.length) {
      graph.copy(cells)
    }
    return false
  })

  graph.bindKey(_createCtrlKey('x'), () => {
    const cells = graph.getSelectedCells()
    if (cells.length) {
      graph.cut(cells)
    }
    return false
  })

  graph.bindKey(_createCtrlKey('v'), () => {
    if (!graph.isClipboardEmpty()) {
      const cells = graph.paste({ offset: 32 })
      graph.cleanSelection()
      graph.select(cells)
    }
    return false
  })
  // #endregion

  // #region 撤销 重做
  graph.bindKey(_createCtrlKey('z'), () => {
    if (graph.history.canUndo()) {
      graph.history.undo()
    }
    return false
  })
  graph.bindKey(_createCtrlKey('z', true), () => {
    if (graph.history.canRedo()) {
      graph.history.redo()
    }
    return false
  })
  // #endregion

  // 删除
  graph.bindKey('backspace', () => {
    const cells = graph.getSelectedCells()
    if (cells.length) {
      graph.removeCells(cells)
    }
  })
}
